import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/todo_item.dart';

/// 待办详情组件（macOS右侧详情面板）
class TodoDetailWidget extends StatefulWidget {
  final TodoItem? selectedTodo;
  final bool isCreateMode;
  final TextEditingController contentController;
  final FocusNode focusNode;
  final Function(bool)? onToggleTop;
  final VoidCallback? onDelete;
  final VoidCallback? onAdd;
  final VoidCallback? onRefresh;
  final Function(String)? onContentChanged; // 新增：内容变化回调
  final Function(bool)? onFavoriteChanged; // 新增：关注状态变化回调

  const TodoDetailWidget({
    super.key,
    required this.selectedTodo,
    required this.isCreateMode,
    required this.contentController,
    required this.focusNode,
    this.onToggleTop,
    this.onDelete,
    this.onAdd,
    this.onRefresh,
    this.onContentChanged,
    this.onFavoriteChanged,
  });

  @override
  State<TodoDetailWidget> createState() => _TodoDetailWidgetState();
}

class _TodoDetailWidgetState extends State<TodoDetailWidget> {
  // 🔑 关键改动：状态由内部管理
  bool _isPreviewMode = true;

  // 用于跟踪任务列表项的索引
  int _checkboxIndex = 0;
  final Map<int, String> _checkboxLines = {};

  @override
  void initState() {
    super.initState();
    // 创建模式下自动获得焦点
    if (widget.isCreateMode) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        widget.focusNode.requestFocus();
      });
    }
  }

  @override
  void didUpdateWidget(TodoDetailWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 切换到创建模式时自动获得焦点
    if (!oldWidget.isCreateMode && widget.isCreateMode) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        widget.focusNode.requestFocus();
      });
    }
    // 切换待办时重置为预览模式
    if (oldWidget.selectedTodo?.id != widget.selectedTodo?.id) {
      setState(() {
        _isPreviewMode = true;
      });
    }
  }

  void _togglePreviewMode() {
    setState(() {
      _isPreviewMode = !_isPreviewMode;
    });
  }


  /// 处理链接点击
  Future<void> _handleLinkTap(String text, String? href, String title) async {
    if (href == null) return;

    final uri = Uri.tryParse(href);
    if (uri == null) return;

    try {
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      // 静默失败
    }
  }

  /// 解析任务列表行
  void _parseTaskLines() {
    _checkboxLines.clear();
    _checkboxIndex = 0;

    final lines = widget.contentController.text.split('\n');
    for (int i = 0; i < lines.length; i++) {
      final line = lines[i];
      if (RegExp(r'^[\s]*-\s*\[[xX ]\]').hasMatch(line)) {
        _checkboxLines[_checkboxIndex] = line;
        _checkboxIndex++;
      }
    }
    _checkboxIndex = 0; // 重置索引供 checkboxBuilder 使用
  }

  /// 构建图标按钮
  Widget _buildIconButton({
    IconData? icon,
    String? svgIcon,
    bool keepSvgColor = false, // 是否保持SVG原始颜色
    required String tooltip,
    bool enabled = true,
    VoidCallback? onPressed,
    String? badge,
  }) {
    return Tooltip(
      message: tooltip,
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          IconButton(
            icon: svgIcon != null
                ? SvgPicture.asset(
                    svgIcon,
                    width: 18,
                    height: 18,
                    colorFilter: keepSvgColor
                        ? null
                        : ColorFilter.mode(
                            enabled ? Colors.grey[700]! : Colors.grey[400]!,
                            BlendMode.srcIn,
                          ),
                  )
                : Icon(
                    icon!,
                    size: 18,
                    color: enabled ? Colors.grey[700] : Colors.grey[400],
                  ),
            onPressed: enabled ? onPressed : null,
            splashRadius: 20,
            constraints: const BoxConstraints(
              minWidth: 36,
              minHeight: 36,
            ),
            padding: EdgeInsets.zero,
          ),
          if (badge != null)
            Positioned(
              right: 0,
              top: 0,
              child: Container(
                padding: const EdgeInsets.all(2),
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.circular(8),
                ),
                constraints: const BoxConstraints(
                  minWidth: 14,
                  minHeight: 14,
                ),
                child: Text(
                  badge,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 9,
                    fontWeight: FontWeight.bold,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 处理任务列表复选框点击
  void _handleCheckboxTap(int index) {
    final currentText = widget.contentController.text;
    final lines = currentText.split('\n');

    int taskIndex = 0;
    for (int i = 0; i < lines.length; i++) {
      if (RegExp(r'^[\s]*-\s*\[[xX ]\]').hasMatch(lines[i])) {
        if (taskIndex == index) {
          // 找到了对应的任务行，切换状态
          if (lines[i].contains('- [x]') || lines[i].contains('- [X]')) {
            // 改为未完成
            lines[i] = lines[i].replaceFirst(RegExp(r'- \[[xX]\]'), '- [ ]');
          } else {
            // 改为已完成
            lines[i] = lines[i].replaceFirst('- [ ]', '- [x]');
          }

          // 更新文本
          final newText = lines.join('\n');

          // 通过回调通知父组件，确保触发自动保存
          if (widget.onContentChanged != null) {
            widget.onContentChanged!(newText);
          }

          // 更新本地显示
          setState(() {
            widget.contentController.text = newText;
          });
          break;
        }
        taskIndex++;
      }
    }
  }

  /// 切换当前行的TODO标记（- [ ]）
  void _toggleTodoMark() {
    final controller = widget.contentController;
    final text = controller.text;
    final selection = controller.selection;

    // 如果没有选中任何文本，使用光标位置
    final cursorPosition = selection.baseOffset;
    if (cursorPosition < 0) return;

    // 找到光标所在行的起始和结束位置
    int lineStart = text.lastIndexOf('\n', cursorPosition - 1) + 1;
    int lineEnd = text.indexOf('\n', cursorPosition);
    if (lineEnd == -1) lineEnd = text.length;

    // 获取当前行的文本
    final currentLine = text.substring(lineStart, lineEnd);

    String newLine;
    int newCursorPosition = cursorPosition;

    // 检查当前行是否已经有TODO标记
    if (currentLine.trimLeft().startsWith('- [ ]')) {
      // 如果有，则删除（包括后面的空格，总共6个字符："- [ ] "）
      final leadingSpaces = currentLine.length - currentLine.trimLeft().length;
      final trimmedContent = currentLine.trimLeft();
      // 检查 "- [ ]" 后面是否有空格
      final hasSpace = trimmedContent.length > 5 && trimmedContent[5] == ' ';
      final removeLength = hasSpace ? 6 : 5; // 如果有空格则删除6个字符，否则删除5个

      newLine = currentLine.substring(0, leadingSpaces) +
                currentLine.substring(leadingSpaces + removeLength);
      // 光标位置调整：如果光标在标记之后，需要向左移动相应字符数
      if (cursorPosition > lineStart + leadingSpaces) {
        newCursorPosition = cursorPosition - removeLength;
      }
    } else {
      // 如果没有，则在行首添加
      final leadingSpaces = currentLine.length - currentLine.trimLeft().length;
      newLine = '${currentLine.substring(0, leadingSpaces)}- [ ] ${currentLine.trimLeft()}';
      // 光标位置调整：向右移动6个字符（"- [ ] "）
      newCursorPosition = cursorPosition + 6;
    }

    // 构建新文本
    final newText = text.substring(0, lineStart) + newLine + text.substring(lineEnd);

    // 通过回调通知父组件，确保触发自动保存
    if (widget.onContentChanged != null) {
      widget.onContentChanged!(newText);
    }

    // 重新请求焦点，避免点击按钮后失去焦点
    widget.focusNode.requestFocus();

    // 在下一帧更新文本和光标位置，确保焦点恢复后光标位置正确
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.value = TextEditingValue(
        text: newText,
        selection: TextSelection.collapsed(offset: newCursorPosition),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 顶部操作栏 - 始终显示
        SafeArea(
          child: Container(
            margin: const EdgeInsets.only(top: 8),
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              children: [
                // 【待办更多操作区域】- 左侧：置顶、收藏、完成、刷新
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 置顶按钮
                      if (!widget.isCreateMode)
                        _buildIconButton(
                          icon: Icons.push_pin_outlined,
                          tooltip: widget.selectedTodo == null
                              ? '置顶'
                              : (widget.selectedTodo!.isTop ? '取消置顶' : '置顶'),
                          enabled: widget.selectedTodo != null,
                          onPressed: widget.selectedTodo == null
                              ? null
                              : () {
                                  if (widget.onToggleTop != null) {
                                    widget.onToggleTop!(!widget.selectedTodo!.isTop);
                                  }
                                },
                        ),
                      // 关注按钮
                      if (!widget.isCreateMode)
                        _buildIconButton(
                          icon: widget.selectedTodo?.isFavorite == true
                              ? Icons.favorite
                              : Icons.favorite_border,
                          tooltip: widget.selectedTodo?.isFavorite == true ? '取消关注' : '关注',
                          enabled: widget.selectedTodo != null,
                          onPressed: widget.selectedTodo == null
                              ? null
                              : () {
                                  if (widget.onFavoriteChanged != null) {
                                    widget.onFavoriteChanged!(!(widget.selectedTodo!.isFavorite));
                                  }
                                },
                        ),
                      // 完成按钮（暂未开发）
                      if (!widget.isCreateMode)
                        _buildIconButton(
                          icon: Icons.check_circle_outline,
                          tooltip: '完成（未开发）',
                          enabled: widget.selectedTodo != null,
                          onPressed: widget.selectedTodo == null
                              ? null
                              : () {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('完成功能暂未开发')),
                                  );
                                },
                        ),
                      // 刷新按钮
                      if (widget.onRefresh != null && !widget.isCreateMode)
                        _buildIconButton(
                          icon: Icons.refresh,
                          tooltip: '刷新',
                          enabled: true,
                          onPressed: widget.onRefresh,
                        ),
                    ],
                  ),
                ),
                const SizedBox(width: 12),
                // 【Markdown操作区域】- 中间：TODO标记
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // TODO标记按钮
                      _buildIconButton(
                        icon: Icons.check_box_outlined,
                        tooltip: '切换TODO标记',
                        enabled: !_isPreviewMode, // 仅在编辑模式下启用
                        onPressed: _toggleTodoMark,
                      ),
                    ],
                  ),
                ),
                const Spacer(),
                // 【待办基本操作区域】- 右侧：新增、星级、预览/编辑、删除
                Container(
                  decoration: BoxDecoration(
                    color: const Color(0xFFEEEEEE),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      // 新建按钮
                      if (widget.onAdd != null && !widget.isCreateMode)
                        _buildIconButton(
                          icon: Icons.add,
                          tooltip: '新建 (⌘N)',
                          enabled: true,
                          onPressed: widget.onAdd,
                        ),
                      // 预览/编辑切换按钮 - 使用 edit.svg
                      _buildIconButton(
                        svgIcon: _isPreviewMode ? 'assets/icons/edit.svg' : null,
                        icon: _isPreviewMode ? null : Icons.visibility_outlined,
                        keepSvgColor: true, // 保持编辑图标原始颜色
                        tooltip: _isPreviewMode ? '编辑' : '预览',
                        enabled: true,
                        onPressed: _togglePreviewMode,
                      ),
                      // 删除按钮 - 使用 delete.svg
                      if (!widget.isCreateMode)
                        _buildIconButton(
                          svgIcon: 'assets/icons/delete.svg',
                          keepSvgColor: true, // 保持删除图标原始颜色
                          tooltip: '删除',
                          enabled: widget.selectedTodo != null,
                          onPressed: widget.selectedTodo == null ? null : widget.onDelete,
                        ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        // 内容区域 - 根据状态显示不同内容
        if (widget.selectedTodo == null && !widget.isCreateMode)
          // 空状态提示
          const Expanded(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.touch_app_outlined,
                    size: 64,
                    color: Colors.grey,
                  ),
                  SizedBox(height: 16),
                  Text(
                    '请选择一个待办事项',
                    style: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                ],
              ),
            ),
          )
        else
          // 文本编辑/预览区域
        Expanded(
          child: Column(
            children: [
              Expanded(
                child: (_isPreviewMode && !widget.isCreateMode)
                    ? Builder(
                        builder: (context) {
                          // 每次重建时解析任务列表
                          _parseTaskLines();

                          // 预处理文本：如果第一行不是标题，自动添加 # 标记
                          String processedText = widget.contentController.text;
                          if (processedText.isNotEmpty) {
                            final lines = processedText.split('\n');
                            final firstLine = lines.first.trim();
                            // 如果第一行不是以 # 开头（不是标题），则添加 # 标记
                            if (firstLine.isNotEmpty && !firstLine.startsWith('#')) {
                              lines[0] = '# ${lines[0]}';
                              processedText = lines.join('\n');
                            }
                          }

                          return SelectionArea(
                            child: GestureDetector(
                              onDoubleTap: _togglePreviewMode,
                              behavior: HitTestBehavior.translucent,
                              child: Markdown(
                              data: processedText,
                              selectable: false, // 使用 SelectionArea 代替，避免冲突
                              padding: const EdgeInsets.all(24),
                              onTapLink: _handleLinkTap,
                            checkboxBuilder: (bool value) {
                              // 获取当前复选框的索引
                              final currentIndex = _checkboxIndex;
                              _checkboxIndex++;

                              return Transform.translate(
                                offset: const Offset(0, 0),
                                child: Checkbox(
                                  value: value,
                                  onChanged: (bool? newValue) {
                                    _handleCheckboxTap(currentIndex);
                                  },
                                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                  visualDensity: const VisualDensity(
                                    horizontal: -4,
                                    vertical: -4,
                                  ),
                                  activeColor: const Color(0xFF4CAF50),
                                  checkColor: Colors.white,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5),
                                  ),
                                  side: BorderSide(
                                    color: value ? const Color(0xFF4CAF50) : const Color(0xFFBDBDBD),
                                    width: 2,
                                  ),
                                ),
                              );
                            },
                            styleSheet: MarkdownStyleSheet(
                    // 基础文本样式 - 参考 markdown-classic
                    p: const TextStyle(
                      fontSize: 14,
                      height: 1.75,
                      color: Color(0xFF353535),
                      letterSpacing: 0.8,
                      wordSpacing: 0.8,
                    ),
                    // 标题样式
                    h1: const TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.w300,
                      color: Color(0xFF2c3e50),
                      height: 1.3,
                    ),
                    h2: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: Color(0xFF2c3e50),
                      height: 1.4,
                    ),
                    h3: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF34495e),
                      height: 1.4,
                    ),
                    h4: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF34495e),
                    ),
                    h5: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF34495e),
                    ),
                    h6: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF34495e),
                    ),
                    // H2边框装饰
                    h2Padding: const EdgeInsets.only(left: 10, top: 20, bottom: 10),
                    // 列表样式
                    listBullet: const TextStyle(
                      color: Color(0xFFf83929),
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                    ),
                    listBulletPadding: const EdgeInsets.only(right: 8),
                    // 链接样式
                    a: const TextStyle(
                      color: Color(0xFF373532),
                      decoration: TextDecoration.underline,
                      decorationColor: Color(0x66373532),
                    ),
                    // 强调样式
                    strong: const TextStyle(
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF353535),
                    ),
                    em: const TextStyle(
                      color: Color(0xFFf83929),
                      fontStyle: FontStyle.italic,
                    ),
                    // 引用样式
                    blockquote: const TextStyle(
                      color: Color(0xFF353535),
                      fontSize: 14,
                      height: 1.75,
                    ),
                    blockquoteDecoration: BoxDecoration(
                      color: const Color(0xFFf5f5f5),
                      borderRadius: BorderRadius.circular(13),
                    ),
                    blockquotePadding: const EdgeInsets.fromLTRB(20, 15, 20, 25),
                    // 代码样式 - 行内代码
                    code: const TextStyle(
                      fontFamily: 'SFMono-Regular, Menlo, Consolas, monospace',
                      fontSize: 12,
                      color: Color(0xFFEB5757),
                      backgroundColor: Color(0x26878378),
                    ),
                    // 代码块样式
                    codeblockDecoration: BoxDecoration(
                      color: const Color(0xB3EEEEEE),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    codeblockPadding: const EdgeInsets.all(16),
                    // 水平分隔线
                    horizontalRuleDecoration: BoxDecoration(
                      border: Border(
                        top: BorderSide(
                          width: 2,
                          color: const Color(0xBFf83929),
                        ),
                      ),
                    ),
                    // 表格样式
                    tableHead: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                      color: Color(0xFF353535),
                    ),
                    tableBody: const TextStyle(
                      fontSize: 13,
                      color: Color(0xFF353535),
                    ),
                    tableBorder: TableBorder.all(
                      color: const Color(0xFFcccccc),
                      width: 1,
                    ),
                    tableCellsPadding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 8,
                    ),
                    // 图片边距和装饰
                    img: const TextStyle(height: 1.0),
                  ),
                              ),
                            ),
                          );
                        },
                      )
                    : TextField(
                  controller: widget.contentController,
                  focusNode: widget.focusNode,
                  style: const TextStyle(
                    fontSize: 14,
                    height: 1.75,
                    color: Color(0xFF353535),
                    letterSpacing: 0.5,
                    wordSpacing: 0.5,
                  ),
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.all(24),
                    hintText: '开始输入...',
                    hintStyle: TextStyle(
                      color: Color(0xFFBDBDBD),
                      fontSize: 14,
                    ),
                  ),
                  maxLines: null,
                  expands: true,
                  textAlignVertical: TextAlignVertical.top,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
